package com.hsgene.common.util.mq;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.*;
import com.hsgene.common.util.basic.UUID32;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 消息队列
 *
 * @author wxf
 * @date 2018/10/26 16:23
 **/
public class MQUtils {

    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(MQUtils.class);

    /**
     * 发送消息
     *
     * @param content  消息
     * @param producer 生产者对象
     * @param topic    主题
     * @param topicTag tag
     * @return
     */
    public static String send(Object content, Producer producer, String topic, String topicTag) {
        if (content == null) {
            return "发送消息不能为空";
        }
        //将对象转成byte
        byte[] bytes = JSON.toJSONString(content).getBytes();
        Message message = new Message(topic, topicTag, bytes);
        //key唯一标志
        message.setKey("dcw" + UUID32.randomUUIDString());
        producer.sendAsync(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                LOGGER.info("send message success,tag is：" + topicTag + ",topic=" + sendResult.getTopic() + ", msgId=" +
                        sendResult.getMessageId());
            }

            @Override
            public void onException(OnExceptionContext context) {
                LOGGER.error("send message failed. topic=" + context.getTopic() + ", msgId=" + context
                        .getMessageId());
            }
        });
        return null;
    }
}
